<?php
namespace app\index\relevan;
use app\index\controller\Common;
use app\index\model\CertBorrowListModel;
use app\index\model\CertCompanyModel;
use app\index\model\CertEmpbuModel;
use app\index\model\CertEmployFeeModel;
use app\index\model\CertEmployModel;
use app\index\model\CertModel;
use app\index\model\FileModel;
use app\index\model\PersonModel;
use app\index\model\CertUseListModel;
use app\index\model\CertUseModel;
use app\index\model\EnginModel;
use app\index\service\CertService;

class CertRelevan extends Common
{
    //员工相关信息
    public function vate_person_info($personid){
        $certnum = CertModel::where(['personid'=>$personid,'deleted_user'=>0])->count();
        $filesnum = FileModel::where(['comid'=>$this->userinfo['comid'],'table'=>'person','mid'=>$personid])->count();

        PersonModel::where(['id'=>$personid])->update([
            'certnum'=>$certnum,
            'filesnum'=>$filesnum,
        ]);
    }

    //人员证书相关信息
    public function vate_cert_info($certid){
        $filesnum = FileModel::where(['comid'=>$this->userinfo['comid'],'table'=>'cert','mid'=>$certid])->count();

        CertModel::where(['id'=>$certid])->update([
            'filesnum'=>$filesnum,
        ]);
    }

    //企业证书相关信息
    public function vate_cert_company_info($certid){
        $info = CertCompanyModel::where(['id'=>$certid])->find();
        $filesnum = FileModel::where(['comid'=>$this->userinfo['comid'],'table'=>'cert_company','mid'=>$certid])->count();

        if($info['pid'] == 0){
            $pidnum = CertCompanyModel::where(['deleted_user'=>0,'pid'=>$certid])->count();
            CertCompanyModel::where(['id'=>$certid])->update(['pidnum'=>$pidnum]);
        }else{
            $pidnum = CertCompanyModel::where(['deleted_user'=>0,'pid'=>$info['pid']])->count();
            CertCompanyModel::where(['id'=>$info['pid']])->update(['pidnum'=>$pidnum]);
        }

        CertCompanyModel::where(['id'=>$certid])->update([
            'filesnum'=>$filesnum,
        ]);
    }

    //借证 审批通过后 更新证书状态
    public function set_cert_goes_yong($data, $bill){
        $list = CertBorrowListModel::where(['mid'=>$data['id']])->select()->toArray();
        foreach ($list as $item){
            if($item['type'] == 1){
                CertModel::where(['id'=>$item['certid']])->update(['goes'=>'借出']);
            }else{
                CertCompanyModel::where(['id'=>$item['certid']])->update(['goes'=>'借出']);
            }
        }
    }
    public function set_cert_goes_shi($data, $bill){
        $list = CertBorrowListModel::where(['mid'=>$data['id']])->select()->toArray();
        foreach ($list as $item){
            if(!$item['guidt'] || $item['guidt'] == '0000-00-00'){
                if($item['type'] == 1){
                    CertModel::where(['id'=>$item['certid']])->update(['goes'=>'在册']);
                }else{
                    CertCompanyModel::where(['id'=>$item['certid']])->update(['goes'=>'在册']);
                }
            }
        }
    }



    public function set_engin_jinglier_jifuer($data){
        $jinglier = CertUseListModel::alias('list')
            ->join('cert_use use','use.id=list.useid')
            ->join('cert cert','cert.id=list.certid')
            ->where(['use.comid'=>$this->userinfo['comid'],'use.deleted_user'=>0,'use.isturn'=>1,'use.status'=>1])
            ->where(['use.enginid'=>$data['enginid'],'use.isreal'=>1,'list.place'=>'项目经理','list.opt'=>1])
            ->value('cert.personid');
        $jifuer = CertUseListModel::alias('list')
            ->join('cert_use use','use.id=list.useid')
            ->join('cert cert','cert.id=list.certid')
            ->where(['use.comid'=>$this->userinfo['comid'],'use.deleted_user'=>0,'use.isturn'=>1,'use.status'=>1])
            ->where(['use.enginid'=>$data['enginid'],'use.isreal'=>1,'list.place'=>'项目技术负责人','list.opt'=>1])
            ->value('cert.personid');

        EnginModel::where(['id'=>$data['enginid']])->update([
            'jinglier' => $jinglier,
            'jifuer' => $jifuer,
        ]);
    }

    public function set_cert_statueuse_engin_yong($data, $bill){
        $exist = CertUseModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['isreal'=>1,'enginid'=>$data['enginid']])->find();
        if($exist){
            CertUseModel::where(['id'=>$exist['id']])->update(['isreal'=>0]);
            $existList = CertUseListModel::where(['useid'=>$exist['id'],'opt'=>1])->select()->toArray();
            foreach ($existList as $eee) {
                $certStatueuse = '空闲';

                $enginList = CertUseListModel::alias('list')
                    ->field('use.enginid,list.certid,list.issuo')
                    ->leftJoin('cert_use use', 'use.id = list.useid')
                    ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                    ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.opt' => 1])
                    ->where(['list.certid'=>$eee['certid']])
                    ->select()->toArray();
                foreach ($enginList as $hhh){
                    $enginInfo = EnginModel::where(['id'=>$hhh['enginid']])->find();
                    if($enginInfo['deleted_user'] == 0 && $enginInfo['status'] == 1){
                        if(in_array($enginInfo['state'], [1,3,7])){
                            $certStatueuse = '在用';
                        }
                    }
                }
                CertModel::where(['id'=>$eee['certid']])->update(['statueuse'=>$certStatueuse]);
            }
        }





        CertUseModel::where(['id'=>$data['id']])->update(['isreal'=>1]);
        $list = CertUseListModel::where(['useid'=>$data['id'],'opt'=>1])->select()->toArray();
        foreach ($list as $vvv){
            $certStatueuse = '空闲';

            $enginList = CertUseListModel::alias('list')
                ->field('use.enginid,list.certid,list.issuo')
                ->leftJoin('cert_use use', 'use.id = list.useid')
                ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.opt' => 1])
                ->where(['list.certid'=>$vvv['certid']])
                ->select()->toArray();
            foreach ($enginList as $hhh){
                $enginInfo = EnginModel::where(['id'=>$hhh['enginid']])->find();
                if($enginInfo['deleted_user'] == 0 && $enginInfo['status'] == 1){
                    if(in_array($enginInfo['state'], [1,3,7])){
                        $certStatueuse = '在用';
                    }
                }
            }
            CertModel::where(['id'=>$vvv['certid']])->update(['statueuse'=>$certStatueuse]);
        }

    }
    public function set_cert_statueuse_engin_shi($data, $bill){
        CertUseModel::where(['id'=>$data['id']])->update(['isreal'=>0]);
        $list = CertUseListModel::where(['useid'=>$data['id'],'opt'=>1])->select()->toArray();
        foreach ($list as $eee) {
            $certStatueuse = '空闲';

            $enginList = CertUseListModel::alias('list')
                ->field('use.enginid,list.certid,list.issuo')
                ->leftJoin('cert_use use', 'use.id = list.useid')
                ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.opt' => 1])
                ->where(['list.certid'=>$eee['certid']])
                ->select()->toArray();
            foreach ($enginList as $hhh){
                $enginInfo = EnginModel::where(['id'=>$hhh['enginid']])->find();
                if($enginInfo['deleted_user'] == 0 && $enginInfo['status'] == 1){
                    if(in_array($enginInfo['state'], [1,3,7])){
                        $certStatueuse = '在用';
                    }
                }
            }

            CertModel::where(['id'=>$eee['certid']])->update(['statueuse'=>$certStatueuse]);
        }

    }
    //更新证书使用情况 更改项目状态的时候处理
    public function set_cert_statueuse_engin($enginid){
        $list = CertUseListModel::alias('list')
            ->field('list.certid')
            ->leftJoin('cert_use use', 'use.id = list.useid')
            ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
            ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.opt' => 1])
            ->where(['use.enginid'=>$enginid])
            ->select()->toArray();

        foreach ($list as $eee) {
            $certStatueuse = '空闲';

            $enginList = CertUseListModel::alias('list')
                ->field('use.enginid,list.certid,list.issuo')
                ->leftJoin('cert_use use', 'use.id = list.useid')
                ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.opt' => 1])
                ->where(['list.certid'=>$eee['certid']])
                ->select()->toArray();
            foreach ($enginList as $hhh){
                $enginInfo = EnginModel::where(['id'=>$hhh['enginid']])->find();
                if($enginInfo['deleted_user'] == 0 && $enginInfo['status'] == 1){
                    if(in_array($enginInfo['state'], [1,3,7])){
                        $certStatueuse = '在用';
                    }
                }
            }
            CertModel::where(['id'=>$eee['certid']])->update(['statueuse'=>$certStatueuse]);
        }

    }

    public function generate_cert_employ_money($minfo){
        $id = $minfo['id'];
        $pay_type = $minfo['pay_type'];
        $personid = $minfo['personid'];
        $c_startdt = $minfo['start_dt'];
        $c_enddt = $minfo['end_dt'];
        $c_money = $minfo['money'];


        if($pay_type == 1){ # 月付
            CertEmployFeeModel::where('mid',$id)->delete();
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            if($ys.'-'.$ms == $ye.'-'.$me) { # 同月
                $md = date('t',strtotime($ys.'-'.$ms.'-01'));
                $money = $c_money * ((int)$de - (int)$ds + 1) / $md;

                $array = [
                    'mid' => $id,
                    'personid' => $personid,
                    'ym' => $ys . '-' . $ms.'-01',
                    'money' => $money,
                ];
                CertEmployFeeModel::create($array);

            } else { # 跨年，判断是否满一年，结束时间是否大于系统生成的结束时间，如果不满一年，按照天数/上一年的总天数*年聘费
                for($year = (int)$ys; $year <= (int)$ye; $year++) {
                    if ($year == $ys && $year == $ye) { // 同年
                        $start_month = (int)$ms;
                        $end_month = (int)$me;
                    } else if ($year == $ys) { // 跨年，初始年份
                        $start_month = (int)$ms;
                        $end_month = 12;
                    } else if ($year == $ye) { // 跨年，结束年份
                        $start_month = 1;
                        $end_month = (int)$me;
                    } else{ // 跨年，中间年份
                        $start_month = 1;
                        $end_month = 12;
                    }

                    for ($i = $start_month; $i <= $end_month; $i++) {
                        if ($i < 10) {
                            $month = '0' . $i;
                        } else {
                            $month = $i;
                        }
                        if($year.'-'.$month == $ys.'-'.$ms){ # 开始月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * ($md - intval($ds) + 1) / $md;
                        }else if($year.'-'.$month == $ye.'-'.$me){ # 结束月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * $de / $md;
                        }else{
                            $money = $c_money;
                        }

                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => $year . '-' . $month.'-01',
                            'money' => $money,
                        ];
                        CertEmployFeeModel::create($array);
                    }
                }
            }

        }else{ # 年付  结束时间 > 开始时间+1年，则满一年   否则计算天数/年天数*金额
            CertEmployFeeModel::where('mid',$id)->delete();
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            $temp_date = $c_startdt;



            for($year = $ys; $year <= $ye; $year++) {
                $temp_ = date('Y-m-d',strtotime($temp_date."+1 year - 1 day"));


                if($temp_ <= $c_enddt){
                    $array = [
                        'mid' => $id,
                        'personid' => $personid,
                        'ym' => date("Y-m-01", strtotime($temp_date)),
                        'money' => $c_money,
                        'startdt' => $temp_date,
                        'enddt' => $temp_,
                    ];

                    $temp_date = date('Y-m-d',strtotime($temp_."+1 day"));
                    CertEmployFeeModel::create($array);
                    if($temp_ == $c_enddt){
                        break;
                    }
                }else{
                    if(substr($temp_,0,7) == substr($c_enddt,0,7)){ # +1年和结束时间为同年, 跨年计算
                        $money = 0;
                        // 首年
                        $year_day = (new CertService())->cal_days_in_year(substr($temp_date,0,4));
                        $day = count_days($temp_date, substr($temp_date,0,4).'-12-31');
                        $money += ($day / $year_day) * $c_money;

                        // 尾年
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $day = count_days($c_enddt, substr($c_enddt,0,4).'-12-31') - 1;
                        $money += (($year_day - $day) / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }else{ # 同年计算
                        $day = count_days($temp_date, $c_enddt) - 1;
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $money = ($day / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }
                    CertEmployFeeModel::create($array);
                    break;
                }
            }
        }

        $this->generate_cert_empbu_money($id);
    }
    public function generate_cert_empbu_money($mid){
        $employ = CertEmployModel::where(['id'=>$mid])->find();
        $buinfo = CertEmpbuModel::where(['mid'=>$mid,'deleted_user'=>0,'isturn'=>1,'status'=>1])->select()->toArray();
        foreach ($buinfo as $item){
            $this->generate_cert_empbu_sonfee($mid,$employ['pay_type'],$employ['personid'],$item['startdt'],$item['enddt'],$item['money']);
        }
    }
    public function generate_cert_empbu_sonfee($id,$pay_type,$personid,$c_startdt,$c_enddt,$c_money){
        if($pay_type == 1){ # 月付
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            if($ys.'-'.$ms == $ye.'-'.$me) { # 同月
                $md = date('t',strtotime($ys.'-'.$ms.'-01'));
                $money = $c_money * ((int)$de - (int)$ds + 1) / $md;

                $array = [
                    'mid' => $id,
                    'personid' => $personid,
                    'ym' => $ys . '-' . $ms.'-01',
                    'money' => $money,
                ];

                $yuanFeeInfo = CertEmployFeeModel::where(['personid'=>$personid,'mid'=>$id,'ym'=>$ys . '-' . $ms.'-01'])->find();
                if($yuanFeeInfo){
                    $xianMoney = round($yuanFeeInfo['money'] + $money, 2);
                    CertEmployFeeModel::where(['id'=>$yuanFeeInfo['id']])->update(['money'=>$xianMoney]);
                }
            } else { # 跨年，判断是否满一年，结束时间是否大于系统生成的结束时间，如果不满一年，按照天数/上一年的总天数*年聘费
                for($year = (int)$ys; $year <= (int)$ye; $year++) {
                    if ($year == $ys && $year == $ye) { // 同年
                        $start_month = (int)$ms;
                        $end_month = (int)$me;
                    } else if ($year == $ys) { // 跨年，初始年份
                        $start_month = (int)$ms;
                        $end_month = 12;
                    } else if ($year == $ye) { // 跨年，结束年份
                        $start_month = 1;
                        $end_month = (int)$me;
                    } else{ // 跨年，中间年份
                        $start_month = 1;
                        $end_month = 12;
                    }

                    for ($i = $start_month; $i <= $end_month; $i++) {
                        if ($i < 10) {
                            $month = '0' . $i;
                        } else {
                            $month = $i;
                        }
                        if($year.'-'.$month == $ys.'-'.$ms){ # 开始月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * ($md - intval($ds) + 1) / $md;
                        }else if($year.'-'.$month == $ye.'-'.$me){ # 结束月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * $de / $md;
                        }else{
                            $money = $c_money;
                        }

                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => $year . '-' . $month.'-01',
                            'money' => $money,
                        ];

                        $yuanFeeInfo = CertEmployFeeModel::where(['personid'=>$personid,'mid'=>$id,'ym'=>$year . '-' . $month.'-01'])->find();
                        if($yuanFeeInfo){
                            $xianMoney = round($yuanFeeInfo['money'] + $money, 2);
                            CertEmployFeeModel::where(['id'=>$yuanFeeInfo['id']])->update(['money'=>$xianMoney]);
                        }
                    }
                }
            }

        }else{ # 年付  结束时间 > 开始时间+1年，则满一年   否则计算天数/年天数*金额
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            $temp_date = $c_startdt;



            for($year = $ys; $year <= $ye; $year++) {
                $temp_ = date('Y-m-d',strtotime($temp_date."+1 year - 1 day"));


                if($temp_ <= $c_enddt){
                    $array = [
                        'mid' => $id,
                        'personid' => $personid,
                        'ym' => date("Y-m-01", strtotime($temp_date)),
                        'money' => $c_money,
                        'startdt' => $temp_date,
                        'enddt' => $temp_,
                    ];

                    $yuanFeeInfo = CertEmployFeeModel::where(['personid'=>$personid,'mid'=>$id])->find();
                    if($yuanFeeInfo){
                        $xianMoney = round($yuanFeeInfo['money'] + $c_money, 2);
                        CertEmployFeeModel::where(['id'=>$yuanFeeInfo['id']])->update(['money'=>$xianMoney]);
                    }


                    if($temp_ == $c_enddt){
                        break;
                    }
                }else{
                    if(substr($temp_,0,7) == substr($c_enddt,0,7)){ # +1年和结束时间为同年, 跨年计算
                        $money = 0;
                        // 首年
                        $year_day = (new CertService())->cal_days_in_year(substr($temp_date,0,4));
                        $day = count_days($temp_date, substr($temp_date,0,4).'-12-31');
                        $money += ($day / $year_day) * $c_money;

                        // 尾年
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $day = count_days($c_enddt, substr($c_enddt,0,4).'-12-31') - 1;
                        $money += (($year_day - $day) / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }else{ # 同年计算
                        $day = count_days($temp_date, $c_enddt) - 1;
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $money = ($day / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }

                    $yuanFeeInfo = CertEmployFeeModel::where(['personid'=>$personid,'mid'=>$id])->find();
                    if($yuanFeeInfo){
                        $xianMoney = round($yuanFeeInfo['money'] + $money, 2);
                        CertEmployFeeModel::where(['id'=>$yuanFeeInfo['id']])->update(['money'=>$xianMoney]);
                    }

                    break;
                }
            }
        }
    }








}
